﻿using System;
using System.Net;
using System.Text;
using System.Windows;

namespace Wpf_IP数字地址
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }
        /// <summary>
        /// 普通IP转化为数字IP
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void BtnIPToNumber_OnClick(object sender, RoutedEventArgs e)
        {
            string ips = TxtIpAddress.Text.Trim();
            IPAddress ip;

            if (ips != string.Empty && IPAddress.TryParse(ips, out ip))
            {
                byte[] bytes = ip.GetAddressBytes();
                // long number = 16777216L * bytes[0] + 65536L * bytes[1] + 256 * bytes[2] + bytes[3];
                long number = ((long)bytes[0] << 24) + ((long)bytes[1] << 16) + ((long)bytes[2] << 8) + (long)bytes[3];
                TxtNumberAddress.Text = number.ToString();
            }
            else
            {
                MessageBox.Show("请输入正确的IP地址", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }



        /// <summary>
        /// 数字IP转化为普通IP
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void BtnNumberToIP_OnClick(object sender, RoutedEventArgs e)
        {
            string numbers = TxtNumberAddress.Text.Trim();
            try
            {
                long number = Convert.ToInt64(numbers);
                long item1 = number >> 24;
                long item2 = (number & 0x00FFFFFF) >> 16;
                long item3 = (number & 0x0000FFFF) >> 8;
                long item4 = number & 0x000000FF;
                TxtIpAddress.Text = item1 + "." + item2 + "." + item3 + "." + item4;

                //long[] mask = { 0x000000FF, 0x0000FF00, 0x00FF0000, 0xFF000000 };
                //long num = 0;
                //StringBuilder ipInfo = new StringBuilder();
                //for (int i = 3; i >= 0; i--)
                //{
                //    num = (number & mask[i]) >> (i * 8);
                //    if (i > 0)
                //    {
                //        ipInfo.Append(num + ".");
                //    }
                //    else
                //    {
                //        ipInfo.Append(num);
                //    }
                //}

                //var kk = ipInfo;

            }
            catch (Exception)
            {
                MessageBox.Show("转换失败，请确认输入的值正确！", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }
    }
}
